import 'dart:async';
import 'dart:io';
import 'package:audio_session/audio_session.dart';
import 'package:fate_blind_box/im/video_model.dart';
import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:fate_blind_box/utils/default/common_config.dart';
import 'package:flutter/material.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:fate_blind_box/routes/page_route_names.dart';
import '../main222.dart';
import '../network/Api.dart';
import '../ui/main/navigator.dart';
import '../utils/loading.dart';
import '../utils/voice_animation_image.dart';
import 'groupdetilspage.dart';
import 'msg_content.dart';
import 'package:flutter_sound_platform_interface/flutter_sound_recorder_platform_interface.dart';
import 'package:path_provider/path_provider.dart';

import 'package:emoji_picker_flutter/emoji_picker_flutter.dart';
import 'package:flutter/foundation.dart' as foundation;
import 'package:get/get.dart';

//群聊天
class GroupChat extends StatefulWidget {
  String groupId;
  String owner;
  bool isFromChoseContact = false; //是否来自选择联系人
  bool isFromShareUrl = false; //是否来自推广分享
  Map<String, String>? dataMap;

  GroupChat(this.groupId, this.owner,
      {Key? key,
      this.isFromChoseContact = false,
      this.isFromShareUrl = false,
      this.dataMap})
      : super(key: key);

  @override
  State<GroupChat> createState() => _GroupChatState();
}

class _GroupChatState extends State<GroupChat> {
  final TextEditingController _messController = TextEditingController();
  // final GlobalKey _formKey = GlobalKey<FormState>();
  VideoModel videoModel = VideoModel();
  bool canSend = false;
  late String centext;
  final List<String> _logText = [];
  Map<String, dynamic> map = {};
  final List<Map> _items = [];
  final ScrollController scrollController = ScrollController();
  FlutterSoundRecorder recorderModule = FlutterSoundRecorder();
  FlutterSoundPlayer playerModule = FlutterSoundPlayer();
  RecordPlayState _state = RecordPlayState.record;
  late StreamSubscription _recorderSubscription;
  late StreamSubscription _playerSubscription;
  late Size _size;

  late double _screenWidth, _screenHeight;
  List<dynamic> lists = [];
  List<dynamic> members = [];
  List<EMMessage>? list = [];
  EMConversation? conversation;
  Map _userInfo = {};
  final FocusNode _focusNode = FocusNode();
  Timer? _timer;

  final int _maxLength = 600;

  // final player = AudioPlayer();

  String _path = "";
  int num = 0;

  String _playerTxt = "";

  final List<String> _assetList = [
    "images/voice_volume_1.png",
    "images/voice_volume_2.png",
    "images/voice_volume_3.png",
    "images/voice_volume_4.png",
    "images/voice_volume_5.png",
    "images/voice_volume_6.png",
    "images/voice_volume_7.png",
  ];

  bool isStop = true;

  int count = 0;

  var isshouw = false;

  bool emojiShowing = false;
  List<String> listr = [];

  bool isSendShare = false;

  @override
  void initState() {
    super.initState();
    // AppWidget.setStatusBlackView(bgColor: ThemeColor.appColor);
    _getUserinfo();
    insertShareMessage();
    initData();
    init();
    _addChatListener();
  }

  insertShareMessage() async {
    if (widget.isFromShareUrl && isSendShare == false) {
      isSendShare == true;
      EMMessage shareMessage = EMMessage.createCustomSendMessage(
        event: 'shareUrl',
        params: widget.dataMap ?? {},
        targetId: widget.groupId,
        chatType: ChatType.GroupChat,
      );
      await EMClient.getInstance.chatManager.sendMessage(shareMessage);
    }
  }

  // 获取环信用户信息
  _getUserinfo() async {
    if (widget.groupId.isEmpty) return;
    final res = await Api.getInstance().getGroupInfo(widget.groupId);
    final data = res['data'];
    print('=======${data}');
    if (data != null) {
      setState(() {
        count = data['count'];
        _userInfo = data['memberEaseGroup'];
      });
    } else {
      if (kDebugMode) {
        print('------获取用户异常---------------' + res['msg']);
      }
    }
  }

  @override
  void dispose() {
    // 移除消息状态监听
    EMClient.getInstance.chatManager
        .removeMessageEvent("YXA6hl6vye2MTQOb2k-1mAKAiA");
    // 移除收消息监听
    EMClient.getInstance.chatManager
        .removeEventHandler("YXA6hl6vye2MTQOb2k-1mAKAiA");
    _focusNode.dispose();
    _messController.dispose();
    if (_timer != null && _timer!.isActive) {
      _timer!.cancel();
    }
    super.dispose();
  }

  initData() async {
    try {
      // 群 ID。
      String convId = widget.groupId;
// 如果会话不存在是否创建。设置为 `true`，则会返回会话对象。
      bool createIfNeed = true;
// 会话类型。详见 `EMConversationType` 枚举类型。
      EMConversationType conversationType = EMConversationType.GroupChat;
// 执行操作。
      conversation = await EMClient.getInstance.chatManager.getConversation(
        convId,
        type: conversationType,
        createIfNeed: true,
      );
      list = await conversation?.loadMessages();
      lists.addAll(list!);
      if (kDebugMode) {
        print('rx----获取回1-----' + list.toString());
        print('收到消息:${list?.length}');
      }
      // 成功加载会话。
      setState(() {
        // if (list!.isEmpty) {
        //   return;
        // }
        // list = list?.reversed.cast<EMMessage>().toList();
        if (kDebugMode) {
          print('rx----获取回-----' + list.toString());
        }
      });
    } on EMError catch (e) {}
  }

  void init() async {
    //开启录音
    await recorderModule.openRecorder();
    //设置订阅计时器
    await recorderModule
        .setSubscriptionDuration(const Duration(milliseconds: 10));

    //设置音频
    final session = await AudioSession.instance;
    await session.configure(AudioSessionConfiguration(
      avAudioSessionCategory: AVAudioSessionCategory.playAndRecord,
      avAudioSessionCategoryOptions:
          AVAudioSessionCategoryOptions.allowBluetooth |
              AVAudioSessionCategoryOptions.defaultToSpeaker,
      avAudioSessionMode: AVAudioSessionMode.spokenAudio,
      avAudioSessionRouteSharingPolicy:
          AVAudioSessionRouteSharingPolicy.defaultPolicy,
      avAudioSessionSetActiveOptions: AVAudioSessionSetActiveOptions.none,
      androidAudioAttributes: const AndroidAudioAttributes(
        contentType: AndroidAudioContentType.speech,
        flags: AndroidAudioFlags.none,
        usage: AndroidAudioUsage.voiceCommunication,
      ),
      androidAudioFocusGainType: AndroidAudioFocusGainType.gain,
      androidWillPauseWhenDucked: true,
    ));
    await playerModule.closePlayer();
    await playerModule.openPlayer();
    await playerModule
        .setSubscriptionDuration(const Duration(milliseconds: 10));
  }

  //动态获取权限
  Future<bool> getPermissionStatus() async {
    Permission permission = Permission.microphone;
    //granted 通过，denied 被拒绝，permanentlyDenied 拒绝且不在提示
    PermissionStatus status = await permission.status;
    if (status.isGranted) {
      return true;
    } else if (status.isDenied) {
      requestPermission(permission);
    } else if (status.isPermanentlyDenied) {
      openAppSettings();
    } else if (status.isRestricted) {
      requestPermission(permission);
    } else {}
    return false;
  }

  /// 暂停/继续播放
  void _pauseResumePlayer() {
    if (playerModule.isPlaying) {
      playerModule.pausePlayer();
      _state = RecordPlayState.play;
      if (kDebugMode) {
        print('===> 暂停播放');
      }
    } else {
      playerModule.resumePlayer();
      _state = RecordPlayState.playing;
      if (kDebugMode) {
        print('===> 继续播放');
      }
    }
    setState(() {});
  }

  /// 开始录音
  _startRecorder() async {
    try {
      var status = await getPermissionStatus();

      Directory tempDir = await getTemporaryDirectory();
      var time = DateTime.now().millisecondsSinceEpoch;
      String path = '${tempDir.path}$time${ext[Codec.amrWB.index]}';

      if (kDebugMode) {
        print('===>  准备开始录音');
      }
      await recorderModule.startRecorder(
          toFile: path,
          codec: Codec.amrWB,
          bitRate: 1411200,
          sampleRate: 44100,
          audioSource: AudioSource.microphone);
      if (kDebugMode) {
        print('===>  开始录音');
      }

      /// 监听录音
      recorderModule.onProgress!.listen((e) {
        DateTime date = DateTime.fromMillisecondsSinceEpoch(
            e.duration.inMilliseconds,
            isUtc: true);

        if (date.second >= _maxLength) {
          if (kDebugMode) {
            print('===>  到达时常停止录音');
          }
          _stopRecorder();
        }
        setState(() {
          if (kDebugMode) {
            print("时间：${date.second}");
          }
          if (kDebugMode) {
            print("当前振幅：${e.decibels}");
          }
          num = date.second;
          setState(() {
            if (e.decibels! > 0 && e.decibels! < 10) {
              if (kDebugMode) {
                print('----${e.decibels}------------');
              }
              // voiceIco = "Asset/message/icon_diyinliang.png";
            } else if (e.decibels! > 20 && e.decibels! < 30) {
              if (kDebugMode) {
                print('----${e.decibels}------------');
              }
              // voiceIco = "Asset/message/icon_zhongyinliang.png";
            } else if (e.decibels! > 30 && e.decibels! < 40) {
              if (kDebugMode) {
                print('----${e.decibels}------------');
              }
              // voiceIco = "Asset/message/icon_gaoyinliang.png";
            } else if (e.decibels! > 40 && e.decibels! < 50) {
              if (kDebugMode) {
                print('----${e.decibels}------------');
              }
              //voiceIco = "Asset/message/icon_zhongyinliang.png";
            } else if (e.decibels! > 50 && e.decibels! < 60) {
              if (kDebugMode) {
                print('----${e.decibels}------------');
              }
              //voiceIco = "Asset/message/icon_diyinliang.png";
            } else if (e.decibels! > 70 && e.decibels! < 100) {
              if (kDebugMode) {
                print('----${e.decibels}------------');
              }
              // voiceIco = "Asset/message/icon_gaoyinliang.png";
            } else {
              //voiceIco = "Asset/message/icon_diyinliang.png";
            }
          });
        });
      });
      setState(() {
        _state = RecordPlayState.recording;
        _path = path;

        if (kDebugMode) {
          print("path == $path");
        }
      });
    } catch (err) {
      setState(() {
        if (kDebugMode) {
          print(err.toString());
        }
        _stopRecorder();
        _state = RecordPlayState.record;
      });
    }
  }

  /// 结束录音
  Future<String?> _stopRecorder() async {
    var s = await recorderModule.stopRecorder();
    if (kDebugMode) {
      print('stopRecorder===> fliePath:$_path');
      // EMMessage.createVoiceSendMessage(targetId: targetId, filePath: _path);
    }
    // widget.stopRecord!(_path, num);

    setState(() {
      _state = RecordPlayState.play;
    });
    return s;
  }

  /// 开始播放
  Future<void> _startPlayer() async {
    try {
      if (await _fileExists(_path)) {
        await playerModule.startPlayer(
            fromURI: _path,
            codec: Codec.aacADTS,
            whenFinished: () {
              print('==> 结束播放');
              _stopPlayer();
              setState(() {});
            });
      } else {
        EasyLoading.showToast("未找到文件路径");
        throw RecordingPermissionException("未找到文件路径");
      }

      _cancelPlayerSubscriptions();
      _playerSubscription = playerModule.onProgress?.listen((e) {
        if (e != null) {
          if (kDebugMode) {
            print(
                "${e.duration} -- ${e.position} -- ${e.duration.inMilliseconds} -- ${e.position.inMilliseconds}");
          }
          DateTime date = DateTime.fromMillisecondsSinceEpoch(
              e.position.inMilliseconds,
              isUtc: true);
          String txt =
              DateTime.fromMillisecondsSinceEpoch(date.millisecondsSinceEpoch)
                  as String;

          setState(() {
            _playerTxt = txt.substring(0, 8);
          });
        }
      }) as StreamSubscription;
      setState(() {
        _state = RecordPlayState.playing;
      });
      if (kDebugMode) {
        print('===> 开始播放');
      }
    } catch (err) {
      if (kDebugMode) {
        print('==> 错误: $err');
      }
    }
    setState(() {});
  }

  /// 结束播放
  Future<void> _stopPlayer() async {
    try {
      await playerModule.stopPlayer();
      if (kDebugMode) {
        print('===> 结束播放');
      }
      _cancelPlayerSubscriptions();
    } catch (err) {
      if (kDebugMode) {
        print('==> 错误: $err');
      }
    }
    setState(() {
      _state = RecordPlayState.play;
    });
  }

  /// 取消录音监听
  void _cancelRecorderSubscriptions() {
    _recorderSubscription.cancel();
  }

  /// 取消播放监听
  void _cancelPlayerSubscriptions() {
    _playerSubscription.cancel();
  }

  ///开始播放，这里做了一个播放状态的回调
  void startPlayer(path, {Function(dynamic)? callBack}) async {
    try {
      if (path.contains('http')) {
        await playerModule.startPlayer(
            fromURI: path,
            codec: Codec.mp3,
            sampleRate: 44000,
            whenFinished: () {
              stopPlayer();
              callBack!(0);
            });
      } else {
        //判断文件是否存在
        if (await _fileExists(path)) {
          if (playerModule.isPlaying) {
            playerModule.stopPlayer();
          }
          await playerModule.startPlayer(
              fromURI: path,
              codec: Codec.amrWB,
              sampleRate: 44000,
              whenFinished: () {
                stopPlayer();
                callBack!(0);
              });
        } else {}
      }
      //监听播放进度
      playerModule.onProgress!.listen((e) {});
      callBack!(1);
    } catch (err) {
      callBack!(0);
    }
  }

  /// 结束播放
  void stopPlayer() async {
    try {
      await playerModule.stopPlayer();
    } catch (err) {}
  }

  ///获取播放状态
  Future getPlayState() async {
    return await playerModule.getPlayerState();
  }

  /// 释放播放器
  void releaseFlauto() async {
    try {
      await playerModule.closePlayer();
    } catch (e) {
      if (kDebugMode) {
        print(e);
      }
    }
  }

  /// 判断文件是否存在
  Future _fileExists(String path) async {
    return await File(path).exists();
  }

  ///申请权限
  void requestPermission(Permission permission) async {
    PermissionStatus status = await permission.request();
    if (status.isPermanentlyDenied) {
      openAppSettings();
    }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  void sendMess() {
    if (!canSend) {
      return;
    }

    // 保证在组件build的第一帧时才去触发取消清空内容
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _messController.clear();
    });
    //  键盘自动收起
    // FocusScope.of(context).requestFocus(FocusNode());

    setState(() {
      canSend = false;
      if (widget.groupId.isEmpty && widget.groupId == null || centext.isEmpty) {
        setState(() {
          scrollController
              .jumpTo(scrollController.position.maxScrollExtent + 50);
        });
        Fluttertoast.showToast(
            msg: "id和内容为空",
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            timeInSecForIosWeb: 1,
            backgroundColor: Colors.white,
            textColor: Colors.black,
            fontSize: 14.0);

        return;
      }

      EMMessage msg = EMMessage.createTxtSendMessage(
        targetId: widget.groupId,
        content: centext,
        chatType: ChatType.GroupChat,
      );
      if (kDebugMode) {
        print('rx--环信群id-------' + widget.groupId);
        print('rx----内容-----' + centext);
      }
      EMClient.getInstance.isConnected().then((value) => {
            if (value)
              {
                EMClient.getInstance.chatManager.sendMessage(msg),
                initData(),
              }
            else
              {
                // Provider.remove('token'),
                // Provider.toLogin(),
              }
          });
    });
  }

  void validateInput(var test) {
    print('..... $test');
    setState(() {
      canSend = test.isNotEmpty;
      centext = test;
    });
  }

  showView() {
    showDialog(
        context: context,
        builder: (context) {
          return Center(
              child: SizedBox(
                  child: Stack(alignment: Alignment.topCenter, children: [
            Container(
                // decoration: BoxDecorationUtil().setFillBoxDecoration(Colors.white, 14.0),
                margin: const EdgeInsets.only(top: 35, right: 52, left: 52),
                child: Column(mainAxisSize: MainAxisSize.min, children: [
                  Row(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        VoiceAnimationImage(
                          _assetList,
                          100,
                          100,
                          isStop,
                        ),
                        // Image(
                        //    image: AssetImage(voiceIco),
                        //    width: 100,
                        //    height: 100),
                      ]),
                ]))
          ])));
        });

    setState(() {});
  }

  void _addChatListener() {
    // 添加消息状态变更监听
    EMClient.getInstance.chatManager.addMessageEvent(
        // ChatMessageEvent 对应的 key。
        "YXA6hl6vye2MTQOb2k-1mAKAiA",
        ChatMessageEvent(
          onSuccess: (msgId, msg) {
            //更新消息
            conversation?.updateMessage(msg);
            initData();
            //_addLogToConsole("发送消息成功");
            setState(() {
              scrollController
                  .jumpTo(scrollController.position.maxScrollExtent + 50);
            });
          },
          onProgress: (msgId, progress) {
            // _addLogToConsole("send message succeed");
          },
          onError: (msgId, msg, error) {
            if (kDebugMode) {
              print('rx----获取失败-----' + error.toString());
              print('消息状态失败');
            }
          },
        ));

    // 添加收消息监听
    EMClient.getInstance.chatManager.addEventHandler(
      // EMChatEventHandler 对应的 key。
      "YXA6hl6vye2MTQOb2k-1mAKAiA",
      EMChatEventHandler(
        onMessagesReceived: (messages) async {
          // player.setAsset('images/music_reveice.mp3');
          // final session = await AudioSession.instance;
          // session.configure(const AudioSessionConfiguration.music());
          // player.play();

          for (var msg in messages) {
            switch (msg.body.type) {
              case MessageType.TXT:
                //收到文字消息
                {
                  EMTextMessageBody body = msg.body as EMTextMessageBody;

                  conversation?.updateMessage(msg);
                  initData();

                  print('rx--环信id-------' + body.toString());
                  print('rx----收到内容-----' + body.content);
                  setState(() {
                    // scrollController.jumpTo(scrollController.position.maxScrollExtent);
                  });
                }
                break;
              case MessageType.IMAGE:
                //收到图片消息
                break;
              case MessageType.VIDEO:
                //收到视频消息

                break;
              case MessageType.LOCATION:
                //收到位置消息

                break;
              case MessageType.VOICE:
                //收到语音消息
                conversation?.updateMessage(msg);
                initData();
                print('收到消息成功---------');
                break;
              case MessageType.FILE:
                //收到文件消息

                break;
              case MessageType.CUSTOM:
                //收到自定义消息
                break;
              case MessageType.CMD:
                {
                  // 当前回调中不会有 CMD 类型消息，CMD 类型消息通过 `EMChatEventHandler#onCmdMessagesReceived` 回调接收
                }
                break;
            }
          }
        },
      ),
    );

    EMClient.getInstance.groupManager.addEventHandler(
        'YXA6hl6vye2MTQOb2k-1mAKAiA',
        EMGroupEventHandler(
            onMemberJoinedFromGroup: (String groupId, String member) =>
                insertCustomMessage(groupId, member)));
  }

  /// 插入自定义消息
  insertCustomMessage(String groupId, String member) async{
    await _getUserinfo();
    Api.getInstance().getUserInfo(member)?.then((value){
      if(value!=null && value['code'] == 0){
        var message = EMMessage.createCustomSendMessage(
          targetId: groupId,
          event: 'addGroup',
          params: {
            "id":'${value['data']['id']}',
            "user_id": member, // 加入者id
            'user_name':'${value['data']['nickName']}',
            "from_type": "通过扫一扫", // 通过什么方式加入
            "from_id": "", // 邀请人id
          },
          chatType: ChatType.GroupChat,
        );
        EMClient.getInstance.chatManager
            .importMessages([message]).then((value) => initData());
      }
    });
    return;

  }

  @override
  Widget build(BuildContext context) {
    String titleStr = _userInfo['groupName'] ?? "";
    return WillPopScope(
        child: AppWidget.navTitleBar(
          title: titleStr + '(' + count.toString() + ')',
          bgColor: ThemeColor.grayF2F4F5Color,
          leftIconColor: Colors.black,
          appBarColor: ThemeColor.grayF2F4F5Color,
          backAction: () {
            if (_focusNode.hasFocus) {
              _focusNode.unfocus();
              _timer = Timer(const Duration(milliseconds: 400), () {
                backToRootTab();
              });
            } else {
              backToRootTab();
            }
          },
          rightActions:CommonConfig.isShowPay()? [
             GestureDetector(
                onTap: () {
                  Get.to(
                      GroupDetailsPage(
                        widget.groupId,
                        widget.owner,
                      ),
                      routeName: PageRouteNames.groupDetailsPage);
                },
                child: SizedBox(
                    width: 56,
                    height: 56,
                    child: Stack(
                      alignment: Alignment.center,
                      children: [
                        Container(
                          color: Colors.transparent,
                          width: 14,
                          height: 14,
                        ),
                        const Icon(
                          Icons.more_horiz,
                          color: Colors.black,
                          size: 30,
                        ),
                      ],
                    )))
          ]:[],
          childWidget: Column(
            children: [
              Flexible(
                child: Container(
                  decoration: BoxDecoration(
                    //背景
                    color: ThemeColor.grayF2F4F5Color,
                    //设置四周边框
                  ),
                  padding:
                      const EdgeInsets.symmetric(horizontal: 14, vertical: 21),
                  child: ListView.builder(
                    controller: scrollController,
                    itemBuilder: (_, index) {
                      if (list?.isNotEmpty == true) {
                        return MessageContent(
                            list!, index, Provider.userEaseName, _assetList);
                      } else {
                        return Container();
                      }
                    },
                    itemCount: list?.length,
                  ),
                ),
              ),
              Container(
                height: 65,
                decoration: BoxDecoration(
                  //背景
                  color: Colors.white,
                  //设置四周边框
                  border: Border.all(width: 1, color: Colors.white),
                ),
                margin: const EdgeInsets.only(left: 0, right: 0, bottom: 0),
                alignment: Alignment.center,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    Visibility(
                      visible: CommonConfig.isShowPay(),
                      child: InkWell(
                        onTap: () {
                          emojiShowing = false;
                          if (isshouw) {
                            isshouw = false;
                            FocusScope.of(context)
                                .requestFocus(_focusNode); // 获取焦点
                          } else {
                            isshouw = true;
                            _focusNode.unfocus();
                          }
                        },
                        child: Container(
                          width: 24,
                          height: 24,
                          margin: const EdgeInsets.only(right: 5),
                          child: Image.asset(
                            'images/ic_volume.png',
                            width: 24,
                            height: 24,
                          ),
                        ),
                      ),
                    ),
                    // ),
                    Offstage(
                      offstage: isshouw,
                      child: SizedBox(
                        child: Form(
                            // key: _formKey,
                            child: SizedBox(
                              width: 200,
                              height: 40,
                              child: SingleChildScrollView(
                                child: TextFormField(
                                    autofocus: false,
                                    maxLines: null,
                                    controller: _messController,
                                    focusNode: _focusNode,
                                    onTap: () {
                                      setState(() {
                                        emojiShowing = false;
                                      });
                                    },
                                    onChanged: validateInput,
                                    keyboardType: TextInputType.text,
                                    decoration: InputDecoration(
                                      isCollapsed: true,
                                      fillColor: const Color(0xffF1F3FB),
                                      filled: true,
                                      contentPadding:
                                          const EdgeInsets.symmetric(
                                              horizontal: 15, vertical: 10),
                                      enabledBorder: const OutlineInputBorder(
                                        /*边角*/
                                        borderRadius: BorderRadius.all(
                                          Radius.circular(30), //边角为30
                                        ),
                                        borderSide: BorderSide(
                                          color: Colors.white54, //边线颜色为黄色
                                          width: 1, //边线宽度为2
                                        ),
                                      ),
                                      focusedBorder: OutlineInputBorder(
                                          borderRadius:
                                              BorderRadius.circular(30),
                                          borderSide: const BorderSide(
                                            color: Colors.white54, //边框颜色为绿色
                                            width: 1, //宽度为5
                                          )),
                                    )),
                              ),
                            )),
                      ),
                    ),
                    Offstage(
                      offstage: !isshouw,
                      child: Listener(
                        onPointerDown: (event) {
                          videoModel.sentimer();
                          //做弹起动画
                          print('长按或点击开始');
                          showView();
                          _startRecorder();
                        },
                        onPointerUp: (event) async {
                          var s = await _stopRecorder();
                          print('长按结束        $s');

                          print('nnn ${videoModel.isStop}');
                          if (videoModel.isStop) {
                            print('ppppppppp');
                            if (videoModel.indexPopTime
                                    .difference(videoModel.lastPopTime) <
                                const Duration(milliseconds: 500)) {
                              if (kDebugMode) {
                                print('长按结束');
                              }

                              if (s.toString().isEmpty) return;
                              EMMessage message =
                                  EMMessage.createVoiceSendMessage(
                                targetId: widget.groupId,
                                filePath: s.toString(),
                                duration: num,
                                chatType: ChatType.GroupChat,
                              );

                              // 发送消息
                              EMClient.getInstance.chatManager
                                  .sendMessage(message);
                              player.setAsset('images/music_send.mp3');
                              final session = await AudioSession.instance;
                              session.configure(
                                  const AudioSessionConfiguration.music());
                              player.play();
                              initData();
                            } else {
                              print('点击结束');
                            }
                          }
                          Navigator.pop(context);
                          if (videoModel.timer.isActive) {
                            videoModel.timer.cancel();
                          }
                        },
                        child: Container(
                          height: 40,
                          margin: const EdgeInsets.only(right: 3, left: 5),
                          padding: const EdgeInsets.symmetric(
                              vertical: 5, horizontal: 60),
                          decoration: const BoxDecoration(
                            color: Color(0xffF1F3FB),
                            borderRadius: BorderRadius.all(Radius.circular(30)),
                          ),
                          child: Text(
                            "按住 说话",
                            textAlign: TextAlign.center,
                            style: TextStyle(
                                color: ThemeColor.textColor,
                                fontSize: 14,
                                fontWeight: FontWeight.normal),
                          ),
                        ),
                      ),
                    ),
                    Container(
                        margin: const EdgeInsets.only(left: 5),
                        child: InkWell(
                          onTap: () {
                            print('表情符号');
                            print('hhhh $isshouw');
                            setState(() {
                              emojiShowing = !emojiShowing;
                              _focusNode.unfocus();
                              if (isshouw) {
                                isshouw = false; // 获取焦点
                              }
                            });
                          },
                          child: Image.asset(
                            'images/ic_emojis.png',
                            width: 24,
                            height: 24,
                          ),
                        )),
                    !canSend
                        ? Visibility(
                            visible: CommonConfig.isShowPay(),
                            child: Container(
                              margin: const EdgeInsets.only(left: 5),
                              child: InkWell(
                                onTap: () {
                                  print('发送图片');
                                  setState(() {
                                    emojiShowing = false;
                                  });
                                  _checkAvatar();
                                },
                                child: Image.asset(
                                  'images/ic_adds.png',
                                  width: 24,
                                  height: 24,
                                ),
                              ),
                            ),
                          )
                        : Container(),
                    Offstage(
                      offstage: !canSend,
                      child: InkWell(
                        onTap: () {
                          listr.clear();
                          list?.clear();
                          sendMess();
                        },
                        child: Container(
                          margin: const EdgeInsets.only(right: 7),
                          padding: const EdgeInsets.only(
                              left: 10, right: 10, top: 8, bottom: 8),
                          decoration: const BoxDecoration(
                            color: Colors.green,
                            borderRadius: BorderRadius.all(Radius.circular(3)),
                          ),
                          child: Text(
                            "确定",
                            style: TextStyle(
                                color: ThemeColor.shadowColor,
                                fontSize: 14,
                                fontWeight: FontWeight.normal),
                          ),
                        ),
                      ),
                    )
                  ],
                ),
              ),
              Offstage(
                offstage: !emojiShowing,
                child: SizedBox(
                    height: 250,
                    child: EmojiPicker(
                      textEditingController: _messController,
                      onBackspacePressed: _onBackspacePressed,
                      onEmojiSelected: (value, e) {
                        print('vv    $e');
                        setState(() {
                          canSend = true;
                          listr.add(e.emoji);
                          centext = listr.join('');
                        });
                      },
                      config: Config(
                        columns: 7,
                        emojiSizeMax: 32 *
                            (foundation.defaultTargetPlatform ==
                                    TargetPlatform.iOS
                                ? 1.30
                                : 1.0),
                        verticalSpacing: 0,
                        horizontalSpacing: 0,
                        gridPadding: EdgeInsets.zero,
                        // initCategory: Category.RECENT,
                        bgColor: const Color(0xFFF2F2F2),
                        indicatorColor: ThemeColor.appColor,
                        iconColor: Colors.grey,
                        iconColorSelected: ThemeColor.appColor,
                        backspaceColor: ThemeColor.appColor,
                        skinToneDialogBgColor: Colors.white,
                        skinToneIndicatorColor: Colors.grey,
                        enableSkinTones: true,
                        recentTabBehavior: RecentTabBehavior.RECENT,
                        recentsLimit: 28,
                        replaceEmojiOnLimitExceed: false,
                        noRecents: const Text(
                          'No Recents',
                          style: TextStyle(fontSize: 20, color: Colors.black26),
                          textAlign: TextAlign.center,
                        ),
                        loadingIndicator: const SizedBox.shrink(),
                        tabIndicatorAnimDuration: kTabScrollDuration,
                        categoryIcons: const CategoryIcons(),
                        buttonMode: ButtonMode.MATERIAL,
                        checkPlatformCompatibility: true,
                      ),
                    )),
              ),
            ],
          ),
        ),
        onWillPop: () async {
          backToRootTab();
          return true;
        });
  }

  _onBackspacePressed() {
    print('bbbbb $listr ${_messController.text.characters.toString()}');
    setState(() {
      canSend = _messController.text.characters.toString().isNotEmpty;
      centext = _messController.text.characters.toString();
    });
  }

  _checkAvatar() {
    if (!kIsWeb) {
      loading(() async {
        final picker = ImagePicker();
        final pickerFile = await picker.pickImage(source: ImageSource.gallery);

        if (pickerFile != null) {
          //裁剪后图片的路径
          String filepath = pickerFile.path;
          if (filepath.toString().isEmpty) return;
          EMMessage message = EMMessage.createImageSendMessage(
            targetId: widget.groupId,
            filePath: filepath.toString(),
            chatType: ChatType.GroupChat,
          );
          EMClient.getInstance.chatManager.sendMessage(message);
        }
      });
    }
  }

  void backToRootTab() {
    if (widget.isFromChoseContact) {
      Get.offAll(
          AppMain(
            currentIndex: 1,
          ),
          routeName: PageRouteNames.appTabPage);
    } else {
      Get.back();
    }
  }
}
